// TODO: some of this needs to be cleaned up

var isPlaylist = false;
var isSingle = false;

var getPlayingItem = function() {
  return $('div.userStreamItem > div.playing');
}

var getDownloadUrl = function($downloadButton) {
  return $downloadButton.parentsUntil('div.userStreamItem').last().data('downloadUrl');
}

var getPlayButton = function($downloadButton) {
  return $downloadButton.parentsUntil('div.userStreamItem').last().find('button[title="Play"]').first();
}

var displayDownloadLink = function($clickedButton) {
  $downloadLink = $('<span>').html('<a href="' + getDownloadUrl($clickedButton) + '">Right click to save</a>');
  $clickedButton.parent().append($downloadLink);
}

// We might not need the following API call anymore
chrome.extension.sendMessage({}, function(response) {
  var readyStateCheckInterval = setInterval(function() {
    if (document.readyState === "complete") {
      clearInterval(readyStateCheckInterval);
    }
  }, 10);
});


chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
	console.log('received message on content script');
	
	if (request.command == 'playlistDataReceived') {
		// we got a playlist here
		isPlaylist = true;
		lookForMedia();
	} else if (request.command == 'trackDataReceived') {
		// we got track data
		if (isPlaylist == false) {
			console.log(request.url);
			lookForMedia();
		}
	} else if (request.command == 'trackUrlReceived') {
		var $currentlyPlaying = getPlayingItem();
		$currentlyPlaying.data('downloadUrl', request.url);
	}
});

var lookForMedia = function() {
	var scContainers = $('div.sound'); // The actual container that is the same on multiple pages
	if (scContainers.length > 0) {
		// We actually have some sound containers
		console.log('found media containers');
		scContainers.each(function(index, container) {
			var mediaHolder = new SCMediaHolder(this);
			mediaHolder.makeDownloadable();
		});
	} else {
		console.log('no media found');
	}
}

var SCMediaHolder = function(container)
{
    this.container = $(container);
    this.obj = this;
    this.isDownloadable = null;
    this.size = null;

    
    this.report = function() {
    	console.log('reporting in');
    };
    
    this.makeDownloadable = function() {
    	if (this.isDownloadable == null) {
        	this.checkExistingDownloadability();
    	}
    	
    	if (this.isDownloadable == false) {
    		this.addDownloadButton();
    		this.isDownloadable = true;
    	}
    };
    
    this.checkExistingDownloadability = function() {
    	var button = this.container.find('button.sc-button-download');
    	if (button.length == 0) {
    		// no download button = not downloadable
    		this.isDownloadable = false;
    	} else {
    		// found download button = is downloadable
    		this.isDownloadable = true;
    	}
    };
    
    this.addDownloadButton = function() {
    	var buttonContainer = this.getButtonContainer();
    	
    	if (buttonContainer != false) {
            var $newButton = $('<button>').
	        	addClass('sc-button sc-button-download sc-button-'+this.size+' sc-button-icon sc-button-responsive').
	        	click(function() {
	        		var $this = $(this);
	        		if (getDownloadUrl($this) === undefined) {
	        			getPlayButton($this).click();
	        			var downloadInterval = setInterval(function() {
	        				if (getDownloadUrl($this) !== undefined) {
	        					clearInterval(downloadInterval);
	        					displayDownloadLink($this);
	        				}
	        			});
	        		} else {
	        			displayDownloadLink($this);
	        		}
	        	});
    		
            buttonContainer.append($newButton);
    	}
    };
    
    this.getButtonContainer = function() {
    	var smallContainer = this.container.find('div.sc-button-group-small');
    	if (smallContainer.length > 0) {
    		this.size = 'small';
    		return smallContainer.first();
    	}
    	
    	var mediumContainer = this.container.find('div.sc-button-group-medium');
    	if (mediumContainer.length > 0) {
    		this.size = 'medium';
    		return mediumContainer.first();
    	}
    	
    	return false;
    }

}
